package com.nakamachizu.controller.mixi;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.TimeZoneLocator;

import com.google.appengine.api.datastore.GeoPt;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.model.LandMarkData;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.session.MixiSessionData;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ErrorsUtil;

public class AddController extends Controller {

    private static final Logger log = Logger.getLogger(AddController.class.getName());
    private String sid;
    
    @Override
    public Navigation run() throws Exception {
        sid = requestScope("sid");
        
        MapDataService mds = new MapDataService();
        MixiSessionData session = mds.getMixiSessionData(sid);
        MapData map = mds.getMapDataMixi(session);
        
        if(map != null && map.getAdminMailAddress().equals(session.getAdminMailAddress())){
            List<LandMarkData> list = map.getLandMarkDataListRef().getModelList();
            if(list == null){
                list = new ArrayList<LandMarkData>();
            }
            if(list.size() < AppConstant.MAX_LANDMARK_NUM()){
                Calendar now = Calendar.getInstance(TimeZoneLocator.get());
                LandMarkData lmd = new LandMarkData();
                String name = requestScope("name");
                String comment = requestScope("comment");
                String icon = requestScope("ico");
                String lat = requestScope("lat");
                String lng = requestScope("lng");
                GeoPt pt = new GeoPt(Float.parseFloat(lat), Float.parseFloat(lng));
                
                //lmd.setMarkType(AppConstant.MARK_TYPE_MIXI());
                lmd.setName(name);
                lmd.setComment(comment);
                lmd.setLatLng(pt);
                lmd.setPcIconName(icon);
                lmd.setMIconName(mds.createMobileLandmarkIconName(list));
                lmd.setEntryDate(now.getTime());
                lmd.setModifyDate(now.getTime());
                lmd.getMapDataRef().setModel(map);
                
                list.add(lmd);
                
                Datastore.put(lmd);
            }else{
                ErrorsUtil.putErrors(errors, request, "message.error.maxlandmark", "landmark_over");
            }
        }
        
        return redirect("/mixi/view?sid=" + sid);
    }
    
    @Override
    protected Navigation handleError(Throwable error) {
        error.printStackTrace();
        log.severe(ErrorsUtil.stackTrace(error));
        return forward("/jsp/pc/mixi/error.jsp");
    }
}
